package com.qishao.oss_service.ossService.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.StringUtils;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.qishao.oss_service.ossService.OssService;
import com.qishao.oss_service.utils.OssConstantPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");//格式化日期

    // aliyun accessKeyId
    @Value("${aliyun.oss.file.accesskey}")
    private String accessKey;

    //ailiyun accessKey的秘钥
    @Value("${aliyun.oss.file.accesskeysecret}")
    private String accessKeySecret;

    //buketNmae
    @Value("${aliyun.oss.file.buketname}")
    private String buKetName;

    //buket外网访问地址
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;


    /*
     * 获取Oss连接
     * */
    private OSS getOssClient() {
        //创建一个OSSClient对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, accessKeySecret);
        //判断Buket仓库是否存在
        if (!ossClient.doesBucketExist(buKetName)) {
            log.info("############### BuketNmae不存在！ #########################");
            //如果不存在那么就使用接口api的方式创建一个buket

            CreateBucketRequest buketrequest = new CreateBucketRequest(buKetName);
            buketrequest.setBucketName(buKetName);//设置Buket仓库名称
            buketrequest.setCannedACL(CannedAccessControlList.PublicRead);//设置权限为公共读 就是可以以允许别人访问
            ossClient.createBucket(buketrequest);
            ossClient.shutdown();//关闭oss连接
            log.info("创建Buket成功！BuKetName：{}", buKetName);
        }
        return ossClient;
    }

    /**
     * 文件上传 的方法
     *
     * @param multipartFile 需要上传的文件
     * @param businessType  文件类型
     * @return 上传成功后返回文件访问的地址
     */
    @Override
    public String UploadDocument(MultipartFile multipartFile, String businessType) {
        //获取oss连接
        OSS ossClient = this.getOssClient();
        //获取文件的后缀名称即文件类型
        String ext = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        String fileName = getFileName(businessType, ext);//获取文件名称
        log.info("fileName:{}", fileName);
        String url = null;

        try {
            //通过ossClient对象来获取文件上传成功后的url
            ossClient.putObject(buKetName, fileName, multipartFile.getInputStream());
            //拼接上传成功后的文件的url
            url = "https://" + buKetName + "." + endpoint + "/" + fileName;
            log.info("文件上传成功  ************  访问地址为：{}", url);
        } catch (Exception e) {
            e.printStackTrace();
//            new RuntimeException(e);
        } finally {
            ossClient.shutdown();
        }
        return url;
    }

    private String getFileName(String businessType, String ext) {
        //上传到oss的那个文件夹目录下，即目标目录，一般是通过fileName来指定目标目录的，目标目录的自动生成规则是：域名/文件类型名/系统时间/文件全称
        String data = sdf.format(new Date());
        if (StringUtils.isNullOrEmpty(businessType)) {//判断文件类型是否为空或''
            businessType = "default";//如果为空那么就直接给一个默认值default
        }
        //为了解决文件重名会覆盖的问题，使用uuid来对文件进行命名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //组合文件名
        String filename = businessType+"/"+ data + uuid + ext;

        return filename;
    }


}
